import React, { Component, PropTypes } from 'react';
import _ from 'underscore';
import { ajax } from './helper/helper';
import moment from 'moment';
import data from './static/index';
import { Icon, Menu, Dropdown, message, Modal, Table, Input } from 'antd';
import SvgIcon from './dashboard/component/svgIcon';

const MenuItemGroup = Menu.ItemGroup;
const SubMenu = Menu.SubMenu;
const Search = Input.Search;


/*header--NewSocialAccount*/
class NewSocialAccount extends Component {
    close() {
        Backbone.history.history.back()
    }
    render() {
        var type = this.props.type;

        return (
            <div className="modal" style={{ display: 'block' }}>
                <div className="modal-dialog">
                    <div className="modal-content box">
                        <div className="modal-header">
                            <button type="button" className="close" data-dismiss="modal" aria-label="Close" onClick={this.close}>
                                <span aria-hidden="true">×</span>
                            </button>
                            <h4 className="modal-title">连接微信账号</h4>
                        </div>
                        <div className="modal-body">
                            <div className="nav-tabs-custom">
                                <ul className="nav nav-tabs">
                                    {type != 2 ? <li className="active"><a href="#tab_1" data-toggle="tab">公众号配置项方式</a></li> : ''}
                                    {type != 1 ? <li className={type == 2 ? "active" : ""}><a href="#tab_2" data-toggle="tab">一键登录授权</a></li> : ''}
                                </ul>
                                <div className="tab-content">
                                    <div className={type != 2 ? "tab-pane active" : "tab-pane"} id="tab_1">
                                        <form className="form-horizontal">
                                            <div className="box-body">
                                                <div className="form-group">
                                                    <label htmlFor="inputEmail3" className="col-sm-4 control-label">公众账号名称</label>
                                                    <div className="col-sm-8">
                                                        <input type="text" className="form-control" id="inputEmail3" placeholder="输入一个名字标识你的公众账号名称" />
                                                    </div>
                                                </div>
                                                <div className="form-group">
                                                    <label htmlFor="inputPassword3" className="col-sm-4 control-label">AppID（应用ID）</label>
                                                    <div className="col-sm-8">
                                                        <input type="text" className="form-control" id="inputPassword3" placeholder="输入AppID" />
                                                    </div>
                                                </div>
                                                <div className="form-group">
                                                    <label htmlFor="inputEmail3" className="col-sm-4 control-label">AppSecret（应用秘钥）</label>
                                                    <div className="col-sm-8">
                                                        <input type="text" className="form-control" id="inputEmail3" placeholder="输入AppSecret" />
                                                    </div>
                                                </div>
                                                <div className="form-group">
                                                    <label htmlFor="inputEmail3" className="col-sm-4 control-label">URL（服务器地址）</label>
                                                    <div className="col-sm-8">
                                                        <input type="text" className="form-control" id="inputEmail3" disabled placeholder="http://wxapi.parllay.cn/wechatcallback?token=K31FAYQ398" />
                                                    </div>
                                                </div>
                                                <div className="form-group">
                                                    <label htmlFor="inputEmail3" className="col-sm-4 control-label">Token（令牌）</label>
                                                    <div className="col-sm-8">
                                                        <input type="text" className="form-control" id="inputEmail3" disabled placeholder="K31FAYQ398" />
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="box-footer">
                                                <button type="submit" className="btn btn-primary btn-block">创建公众号连接</button>
                                            </div>
                                        </form>
                                    </div>
                                    <div className={type == 2 ? "tab-pane active" : "tab-pane"} id="tab_2">
                                        <div className="box-body">
                                            <div className="form-group">
                                                <p>烽火台是腾讯一键登录授权官方认证平台。一键登录授权是腾讯为公众号第三方平台提供给公众号运营者在面向垂直行业需求时，可以通过一键登录授权给第三方开发者，来完成相关能力。</p>
                                                <p>一键登录授权的官方说明 <a href="https://open.weixin.qq.com" target="_blank">https://open.weixin.qq.com</a></p>
                                            </div>
                                        </div>
                                        <div className="box-footer">
                                            <form className="form-horizontal">
                                                <button type="submit" className="btn btn-primary btn-block">一键登录授权</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

/*header--SocialAccount*/
// class AccountItemPlus extends Component {
//     render() {
//         var data = this.props.data,
//             setSocialAccount = this.props.setSocialAccount,
//             openID = this.props.openID;

//         return (
//             <li className="user user-menu user-plus" title="新增账号" >
//                 <a href="#bind-social-account"><i className="fa fa-plus user-image" alt="新增账号" ></i></a>
//             </li>
//         )
//     }
// }

class AccountItem extends Component {
    setChosen() {
        var data = this.props.data,
            index = this.props.index,
            setSocialAccount = this.props.setSocialAccount;
        setSocialAccount(data);
        ajax({
            type: 'post',
            url: '/setsocialaccount',
            data: { chosen: index },
            success: function (data) {
                if (!data.error) { console.log(data) }
            }
        })
    }
    render() {
        var data = this.props.data,
            openID = this.props.openID;

        return (
            <li className={data.openID == openID ? "user user-menu active" : "user user-menu"} onClick={() => this.setChosen()} title={data.name} >
                <a href="javascript:void(0)"><img src={data.src} className="user-image" alt={data.name} /></a>
            </li>
        )
    }
}

class SocialAccount extends Component {
    constructor(props) {
        super(props);

        props.aboutSocialAccount.getSocialAccount(this)
        this.state = {
            data: []
        }
    }
    render() {
        var aboutSocialAccount = this.props.aboutSocialAccount,
            setSocialAccount = aboutSocialAccount.setSocialAccount,
            openID = aboutSocialAccount.openID,
            data = this.state.data,
            list = data.map(function (i, index) {
                return (
                    <AccountItem key={index} index={index} data={i} setSocialAccount={setSocialAccount} openID={openID} />
                )
            });
        //list.push(<AccountItemPlus key={-1} />)

        return (
            <ul className="nav navbar-nav social-account">
                {list}
            </ul>
        )
    }
}

/*header--UserAccount*/
class UserAccount extends Component {
    constructor(props) {
        super(props);
        props.getAllStores(this);
        this.state = {
            stores: [],
            visible: false,
            param: { current: 1, pageSize: 5 },
            loading: false
        }
    }
    componentDidMount() {
        this.setState({
            loading: true
        });
        this.props.getAllStores(this, this.state.param);
    }
    changeStore(e) {
        if (e.key == 'user') {
            location.href = '/setprofile';
        } else if (e.key == 'logout') {
            location.href = '/logout';
        } else if (e.key == 'all') {
            this.setState({
                visible: true
            });
        } else {
            let store = this.state.stores.find(item => { return item.storeId == e.key });
            this.props.changeStore(e.key, store.storeName);
        }

    }
    closeHandle() {
        this.setState({
            visible: false
        });
    }
    changePageHandle(pagination) {
        const param = this.state.param;
        param.current = pagination.current;
        this.setState({
            param,
            loading: true
        });
        this.props.getAllStores(this, param);
    }
    searchStore(name) {
        const param = this.state.param;
        param.current = 1;
        param.keyword = name;
        this.setState({
            param,
            loading: true
        });
        this.props.getAllStores(this, param);
    }
    render() {
        var state = this.state;
        const { changeStore } = this.props;
        const searchStore = this.searchStore.bind(this);
        const menu = (
            <Menu onClick={this.changeStore.bind(this)}>
                {/* <Menu.Item key="user"><Icon type="user" />个人中心</Menu.Item> */}
                <Menu.Item key="logout"><Icon type="logout" />退出</Menu.Item>
                <Menu.Divider />
                {
                    user.role > 1 ?
                        state.stores && state.stores.map(item => {
                            return <Menu.Item key={item.storeId}>{item.storeName}</Menu.Item>
                        })
                        : ''
                }
                {
                    user.role > 1 ? <Menu.Item key="all">所有门店</Menu.Item> : ''
                }

            </Menu>
        );
        const columns = [
            {
                title: '门店名称',
                dataIndex: 'storeName',
                key: 'storeId',
                render: (text, data) => <a onClick={() => changeStore(data.storeId, data.storeName)} href="javascript:void(0)">{text}</a>
            },
            {
                title: '门店地址',
                dataIndex: 'address',
                key: 'address'
            },
            {
                title: '门店电话号码',
                dataIndex: 'phone',
                key: 'phone'
            },
            {
                title: '门店创建时间',
                dataIndex: 'createDatetime',
                key: 'createDatetime',
                render: text => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
            }
        ];

        return (
            <div className="navbar-custom-menu">
                {/* <ul className="nav navbar-nav">
                    <li className="dropdown user user-menu">
                        <a href="javascript:void(0)" className="dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
                            <img src={user.profile_image || '/dist/images/default.png'} className="user-image" alt="User Image" />
                            <span className="hidden-xs">{user.nickName}</span>
                        </a>
                        <ul className="dropdown-menu">
                            <li className="user-header">
                                <img src={user.profile_image || '/dist/images/default.png'} className="img-circle" alt="User Image" />
                                <p>
                                    {user.name}
                                    <small>注册自 {moment(user.registDatetime).format('YYYY-MM-DD HH:mm:ss')}</small>
                                </p>
                            </li>
                            <li className="user-footer">
                                <div className="pull-left">
                                    <a href="/setprofile" className="btn btn-default btn-flat">个人中心</a>
                                </div>
                                <div className="pull-right">
                                    <a href="/logout" className="btn btn-default btn-flat">退出</a>
                                </div>
                            </li>
                        </ul>
                    </li>
                </ul> */}

                <Dropdown overlay={menu}>
                    <a className="ant-dropdown-link" href="javascript:void(0)">
                        <span style={{ backgroundImage: `url('http://47.104.2.156/${user.headImage}'), url('/dist/images/default.png')` }}></span>
                        {user.nickName}<Icon type="down" />
                    </a>
                </Dropdown>
                <Modal
                    visible={state.visible}
                    title="所有门店"
                    footer={null}
                    onCancel={this.closeHandle.bind(this)}
                >
                    <Search
                        placeholder="输入门店名称"
                        style={{ width: 200, marginBottom: 10 }}
                        onSearch={value => searchStore(value)}
                    />
                    <Table pagination={state.param} rowKey={record => record.storeId} columns={columns} loading={state.loading} columns={columns} dataSource={state.stores} onChange={this.changePageHandle.bind(this)} />
                </Modal>
            </div>
        )
    }
}

/*header--BusinessAccount*/
class BusinessItem extends Component {
    render() {
        var data = this.props.data,
            url = data.active ? 'javascript:void(0)' : data.url;

        return (
            <li className={data.active ? 'active' : null}><a href={url}>{data.name}</a></li>
        )
    }
}

class BusinessAccount extends Component {
    constructor(props) {
        super(props);

        props.getBusinessAccount(this);
        this.state = {
            data: []
        }
    }
    render() {
        const { data } = this.state;
        var businessName = '请选择企业账号',
            list = data.map(function (i, index) {
                if (i.active) {
                    businessName = i.name
                }
                return (
                    <BusinessItem key={index} data={i} />
                )
            });

        return (
            <div className="navbar-custom-menu">
                <ul className="nav navbar-nav">
                    <li className="dropdown">
                        <a href="javascript:void(0)" className="dropdown-toggle">{businessName} <span className="caret"></span></a>
                        <ul className="dropdown-menu" style={{ left: 'auto', right: 0 }}>
                            {list}
                        </ul>
                    </li>
                </ul>
            </div>
        )
    }
}


/*header--main*/
class Header extends Component {
    constructor(props) {
        super(props);
        this.state = {
            collapse: false
        }
    }
    componentWillMount() {
        var collapse = localStorage.getItem("fht-v2-collapse") === 'true';
        this.setState({
            collapse: collapse
        });
        document.body.className = ('skin-blue sidebar-mini fixed' + (!collapse ? ' sidebar-collapse' : ''));
    }
    toggle() {
        var collapse = document.body.className.indexOf('sidebar-collapse') >= 0;
        this.setState({
            collapse: collapse
        });
        var aboutSocialAccount = this.props.aboutSocialAccount;
        document.body.className = ('skin-blue sidebar-mini fixed' + (!collapse ? ' sidebar-collapse' : ''));
        localStorage.setItem("fht-v2-collapse", collapse);
        /*ajax({
            type:'post',
            url:'/setcollapse',
            data:{
                collapse:!collapse
            },
            dataType:'json',
            success:function(data){
                console.log(data)
            }
        })*/
        aboutSocialAccount.toggle && aboutSocialAccount.toggle(collapse)
    }
    render() {
        var aboutSocialAccount = this.props.aboutSocialAccount,
            getBusinessAccount = this.props.getBusinessAccount,
            getAllStores = this.props.getAllStores,
            changeStore = this.props.changeStore;
        let collapse = this.state.collapse;
        return (
            <header className="main-header">
                {/* <a href="/" className="logo">
                    <span className="logo-mini"><b style={{ fontSize: 20 }}>叮当</b></span>
                    <span className="logo-lg"><b>叮</b>当一下</span>
                </a> */}
                <a href="javascript:void(0)" className={"sidebar-toggle" + (collapse ? " sidebar-toggle-spread" : "")} data-toggle="offcanvas" role="button" onClick={() => this.toggle()}>
                    <span className="sr-only">Toggle navigation</span>
                </a>
                {/* <nav className="navbar navbar-static-top">
                    <a href="javascript:void(0)" className="sidebar-toggle" data-toggle="offcanvas" role="button" onClick={() => this.toggle()}>
                        <span className="sr-only">Toggle navigation</span>
                    </a>
                    {/* <SocialAccount aboutSocialAccount={aboutSocialAccount} />}
                    <div className="navbar-custom-menu">
                        <ul className="nav navbar-nav">
                            {/*<BusinessAccount getBusinessAccount={getBusinessAccount} />}
                            <UserAccount getUserInfo={getUserInfo} />
                        </ul>
                    </div>
                </nav> */}
                <div className="slds-global-header slds-grid slds-grid_align-spread">
                    <div className="slds-global-header__item">
                        <div className="slds-global-header__logo">
                            <a href="/">
                                <img src="/dist/images/logo.png" alt="" />
                            </a>
                        </div>
                    </div>
                    {/* <div className="slds-global-header__item slds-global-header__item_search">
                        <GlobalSearch
                            expanded={props.expanded}
                            value={props.searchingFor}
                        />
                    </div> */}
                    <ul className="slds-global-header__item slds-grid slds-grid_vertical-align-center">
                        {/* <li className="slds-grid"><span className="slds-dropdown-trigger slds-dropdown-trigger_click"><button className="slds-button slds-button_icon slds-button_icon slds-button_icon-container slds-button_icon-small slds-global-header__button_icon slds-m-left_none" title="View Favorites"><Icon type="star-o" style={{ fontSize: 22 }} /><span className="slds-assistive-text">View Favorites</span></button></span></li> */}
                        {/* <li className="slds-dropdown-trigger slds-dropdown-trigger_click"><button className="slds-button slds-button_icon slds-button_icon slds-button_icon-container slds-button_icon-small slds-global-header__button_icon" title="Help and Training"><Icon type="plus-circle" style={{ fontSize: 22 }} /><span className="slds-assistive-text">Help and Training</span></button></li> */}
                        {/* <li className="slds-dropdown-trigger slds-dropdown-trigger_click"><button className="slds-button slds-button_icon slds-button_icon slds-button_icon-container slds-button_icon-small slds-global-header__button_icon" title="Help and Training"><Icon type="question" style={{ fontSize: 22 }} /><span className="slds-assistive-text">Help and Training</span></button></li> */}
                        {/* <li className="slds-dropdown-trigger slds-dropdown-trigger_click"><button className="slds-button slds-button_icon slds-button_icon slds-button_icon-container slds-button_icon-small slds-global-header__button_icon" title="Setup"><Icon type="setting" style={{ fontSize: 22 }} /><span className="slds-assistive-text">Setup</span></button></li> */}
                        {/* <li className="slds-dropdown-trigger slds-dropdown-trigger_click"><button className="slds-button slds-button_icon slds-button_icon slds-button_icon-container slds-button_icon-small slds-global-header__button_icon" title="Notifications"><Icon type="notification" style={{ fontSize: 22 }} /><span className="slds-assistive-text">Notifications</span></button></li> */}
                        <li className="slds-dropdown-trigger slds-dropdown-trigger_click slds-m-left_x-small">
                            <UserAccount getAllStores={getAllStores} changeStore={changeStore} />
                        </li>
                    </ul>
                </div>
            </header>
        )
    }
}

/*sidebar*/
class SubTreeView extends Component {
    render() {
        var data = this.props.data,
            path = location.pathname,
            title = document.title.split('-')[0],
            active = path.indexOf(data.url) >= 0 || title == data.name;

        return (
            <li className={active ? "active" : ""}>
                <a href={"/" + data.url}>
                    <i className="fa fa-circle-o"></i> {data.name}
                </a>
            </li>
        )
    }
}

class TreeView extends Component {
    constructor() {
        super();
        this.state = {
            active: false
        }
    }
    toggleMenu() {
        this.setState({
            active: !this.state.active
        })
    }
    render() {
        var data = this.props.data,
            path = location.pathname,
            active = path.indexOf(data.url) >= 0 || this.state.active,
            subData = data.sub,
            toggleMenu = this.toggleMenu.bind(this),
            subHtml = '';

        if (subData) {
            subHtml = <ul className="treeview-menu menu-open">
                {subData.map(function (i, index) {
                    return (
                        <SubTreeView key={index} data={i} />
                    )
                })}
            </ul>
        }
                                    
        return (
            <li className={active ? "treeview active" : "treeview"}>
                <a href={subData ? "javascript:void(0)" : ('/' + data.url)} onClick={toggleMenu}>
                    <i className={"fa " + data.icon}></i>
                    <span> {data.name}</span>
                    <i className="fa fa-angle-left pull-right"></i>
                </a>
                {subHtml}
            </li>
        )
    }
}

class SidebarMenu extends Component {
    constructor(props) {
        super(props);
        let newData = [];
        if (data.sidebar) {
            data.sidebar.forEach(item => {
                newData.push(item);
            })
        }
        this.state = {
            data: newData
        }
    }
    render() {
        var data = this.state.data.map(function (i, index) {
            return (
                <TreeView key={index} data={i} />
            )
        });
        return (
            <aside className="main-sidebar">
                <section className="sidebar">
                    <div className="user-panel"></div>
                    <ul className="sidebar-menu">
                        {data}
                    </ul>
                </section>
            </aside>
        )
    }
}

/*wrapper*/
export class ContentHeader extends Component {
    render() {
        var ele = document.getElementById('wrapper'),
            { title, socialAccount, subtitle, icon, sprite, iconClassName } = this.props;

        return (
            // <section className="content-header">
            //     {
            //         title ? <h1>{title}<small>{subtitle}</small></h1> : ''
            //     }

            //     {this.props.children}
            // </section>
            <header className="site site-masthead slds-grid slds-wrap">
                {
                    icon ?
                        <span style={{ marginRight: 10 }} className={`slds-icon_container ${iconClassName}`}>
                            <SvgIcon className="slds-icon slds-icon--large" sprite={sprite} symbol={icon} />
                        </span>
                        : ''
                }
                {
                    title ?
                        <div className="site-masthead-title slds-has-flexi-truncate slds-align-middle">
                            <h1>{title}</h1>
                            <span>{subtitle}</span>
                        </div>
                        : ''
                }
                <div className="slds-p-vertical_x-small slds-align-middle">
                    <div className="slds-is-relative">
                        <div className="slds-m-right_xx-small" style={{ display: "inline" }}>
                            {this.props.children}
                        </div>
                    </div>
                </div>
            </header >
        )
    }
}

export default class Wrapper extends Component {
    constructor() {
        super();

        this.state = {
            socialAccount: {
                openID: null
            }
        }
    }
    componentWillMount() {
        //$.AdminLTE.layout.fix()
    }
    setSocialAccount(account) {
        this.props.setSocialAccount(account);
        this.setState({
            socialAccount: account
        })
    }
    render() {
        const { getSideBar, getSocialAccount, getBusinessAccount, getAllStores, changeStore, onToggle } = this.props;
        const { socialAccount } = this.state;
        const openID = socialAccount.openID;
        var children = this.props.children;

        return (
            <div className="wrapper">
                <Header aboutSocialAccount={{
                    getSocialAccount: getSocialAccount,
                    setSocialAccount: this.setSocialAccount.bind(this),
                    toggle: onToggle,
                    openID: openID
                }}
                    getBusinessAccount={getBusinessAccount}
                    getAllStores={getAllStores}
                    changeStore={changeStore} />
                <SidebarMenu />
                <div className="content-wrapper" id="content">
                    {children}
                </div>
                <div id="modal"></div>
            </div>
        )
    }
}

Wrapper.defaultProps = {
    getSideBar: function (sidebar) {
        ajax({
            type: 'get',
            url: '/sidebar',
            dataType: 'json',
            success: function (data) {
                if (data) {
                    data = JSON.parse(data);
                    sidebar.setState({
                        data: data
                    })
                }
            }
        })
    },
    getSocialAccount: function (accounts) {
        var self = this;
        ajax({
            type: 'get',
            url: '/socialaccount',
            dataType: 'json',
            success: function (data) {
                if (data) {
                    data = JSON.parse(data);
                    accounts.setState({
                        data: data
                    });
                    var chosen = _.find(data, function (i) { return i.chosen >= 0 }) || 0;
                    self.setSocialAccount(chosen)
                }
            }
        })
    },
    getBusinessAccount: function (accounts) {
        var self = this;
        ajax({
            type: 'get',
            url: '/businessaccount',
            dataType: 'json',
            success: function (data) {
                if (data) {
                    data = JSON.parse(data);
                    accounts.setState({
                        data: data
                    })
                }
            }
        })
    },
    getAllStores: function (thisE, params) {
        // ajax({
        //     url: `/settings/search/team`,
        //     type: 'GET',
        //     data: { page: params && params.current || 1, size: params && params.pageSize || 5, keyword: params && params.keyword || '' },
        //     success: (data) => {
        //         try {
        //             data = JSON.parse(data);
        //         } catch (error) {
        //
        //         }
        //         if (data.success) {
        //             const param = thisE.state.param;
        //             param.total = data.result.total;
        //             thisE.setState({
        //                 loading: false,
        //                 stores: data.result.data,
        //                 param
        //             });
        //         } else {
        //             thisE.setState({
        //                 stores: []
        //             });
        //         }
        //     }
        // });
    },
    changeStore: function (storeId, storeName) {
        ajax({
            url: '/change/store',
            type: 'GET',
            data: { storeId, storeName },
            success: (data) => {
                try {
                    data = JSON.parse(data);
                } catch (error) {

                }
                if (data.success) {
                    location.reload();
                } else {
                    message.error('出现异常，请刷新页面重试!');
                }
            }
        });
    },

}


